# -*- coding: utf-8 -*-
# --------------------------------------
# @Time    : 2025/8/25 9:56
# @File    : model_to_list.py
# @Project : app
# @Author  : CHH
# @Desc    : Windows   文件描述
# @Copyright : © 2025 HORDOR . All rights reserved.
# @Version : 1.0.0
# --------------------------------------
# 表模型结果，转换为可以jsonify化的列表和字典混合的JavaScript数据[{}]，
import datetime


def model2list(result):
    lis = []
    for row in result:
        dic = {}
        for k, v in row.__dict__.items():
            if not k.startswith('_sa_instance_state'):  # 多一个无关键值对，需要去掉
                # 如果是datetime类型将其转换为字符串
                if isinstance(v, datetime.datetime):
                    v = v.strftime("%Y-%m-%d %H:%M:%S")
                dic[k] = v
        lis.append(dic)
    return lis


# 联表模型转成列表供调用
# SQLAlchemy连接查询两张表的结果集转换为[{},{}]
# Comment, Users,  [((Comment, Users),(Comment, Users),(Comment, Users))]
def model_join_list(result):
    list = []  # 定义列表用于存放所有行
    for obj1, obj2 in result:
        dict = {}
        for k1, v1 in obj1.__dict__.items():
            if not k1.startswith('_sa_instance_state'):
                if not k1 in dict:  # 如果字典中已经存在相同的 Key 则跳过
                    # 如果是datetime类型将其转换为字符串
                    if isinstance(v1, datetime.datetime):
                        v1 = v1.strftime("%Y-%m-%d %H:%M:%S")
                    dict[k1] = v1
        for k2, v2 in obj2.__dict__.items():
            if not k2.startswith('_sa_instance_state'):
                if not k2 in dict:  # 如果字典中已经存在相同的 Key 则跳过
                    # 如果是datetime类型将其转换为字符串
                    if isinstance(v2, datetime.datetime):
                        v2 = v2.strftime("%Y-%m-%d %H:%M:%S")
                    dict[k2] = v2
        list.append(dict)
    return list
